package com.bread.tliaswebmanagement.service.impl;

import com.bread.tliaswebmanagement.exception.DeptDeleteFailException;
import com.bread.tliaswebmanagement.mapper.DeptMapper;
import com.bread.tliaswebmanagement.mapper.EmpMapper;
import com.bread.tliaswebmanagement.pojo.Dept;
import com.bread.tliaswebmanagement.pojo.Emp;
import com.bread.tliaswebmanagement.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<Dept> findAll() {
        return deptMapper.findAll();
    }

    @Override
    public void deleteById(Integer id) throws DeptDeleteFailException {
        List<Emp> empList = empMapper.selectByDeptId(id);
        if (empList != null && !empList.isEmpty()){
            // 有员工，不能删除
            throw new DeptDeleteFailException("对不起，当前部门下有员工，不能直接删除！");
        }else {
            deptMapper.deleteById(id);
        }

    }

    @Override
    public void add(Dept dept) {
        LocalDateTime now = LocalDateTime.now();
        dept.setCreateTime(now);
        dept.setUpdateTime(now);
        deptMapper.insert(dept);
    }

    @Override
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }

    @Override
    public void update(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.update(dept);
    }
}
